<script setup lang="ts">
import { ref, computed } from 'vue';
import { useAppStore } from '@/store';
import { useThemeStore } from '@/store/modules/theme';
import { ElCard, ElAvatar, ElDescriptions, ElDescriptionsItem, ElTag, ElDivider, ElButton, ElUpload, ElMessage } from 'element-plus';
import { Edit, UploadFilled } from '@element-plus/icons-vue';
import { $t } from '@/locales';
import { userGenderRecord, enableStatusRecord } from '@/constants/business';
import { useAuthStore } from '@/store/modules/auth';

const appStore = useAppStore();
const themeStore = useThemeStore();
const authStore = useAuthStore();

const userInfo = computed(() => authStore.userInfo);

// For avatar upload
const avatarUrl = ref(userInfo.value.userImages || 'http://127.0.0.1:9000/image-bucket/20250514/fbee6c07a7d24746884456b56b6a21bfd1ee7e8c-5af4-462a-bf59-e58a053dba21.jpg');
const uploading = ref(false);

// Example user stats
const userStats = [
  { label: $t('page.userCenter.loginCount'), value: '128' },
  { label: $t('page.userCenter.lastLogin'), value: new Date().toLocaleString() },
  { label: $t('page.userCenter.registerDate'), value: '2024-01-01' },
];

const recentActivities = [
  { date: '2024-05-14', action: $t('page.userCenter.activity.login'), time: '15:30' },
  { date: '2024-05-13', action: $t('page.userCenter.activity.updateProfile'), time: '09:45' },
  { date: '2024-05-10', action: $t('page.userCenter.activity.changePassword'), time: '11:20' },
];

// Handle avatar upload
const handleAvatarSuccess = (res) => {
  if (res && res.url) {
    avatarUrl.value = res.url;
    ElMessage.success($t('page.userCenter.avatarUploadSuccess'));
  }
  uploading.value = false;
};

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error($t('page.userCenter.avatarUploadTypeError'));
    return false;
  }
  if (!isLt2M) {
    ElMessage.error($t('page.userCenter.avatarUploadSizeError'));
    return false;
  }
  uploading.value = true;
  return true;
};
</script>

<template>
  <div class="user-center-container p-20px">
    <div class="user-center-header flex gap-24px flex-wrap">
      <!-- User Avatar and Basic Info Card -->
      <ElCard class="flex-1 min-w-300px" :body-style="{ padding: '20px' }">
        <div class="flex items-start gap-20px flex-wrap md:flex-nowrap">
          <div class="avatar-container relative">
            <ElAvatar :size="100" :src="avatarUrl" />
            <div class="avatar-upload">
              <ElUpload
                class="avatar-uploader"
                action="/api/user/avatar" 
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <ElButton 
                  type="primary" 
                  circle 
                  size="small" 
                  class="upload-button" 
                  :icon="Edit" 
                  :loading="uploading"
                />
              </ElUpload>
            </div>
          </div>
          <div class="user-info flex-1">
            <h2 class="text-xl font-semibold mb-8px">{{ userInfo.userName || 'Admin User' }}</h2>
            <p class="text-gray opacity-80 mb-12px">{{ userInfo.nickName || 'System Administrator' }}</p>
            
            <div class="flex flex-wrap gap-8px mt-16px">
              <ElTag 
                v-for="role in userInfo.roles" 
                :key="role" 
                :type="themeStore.themeColor.primary"
                effect="light"
              >
                {{ role }}
              </ElTag>
            </div>
            
            <div class="user-stats flex gap-16px mt-16px">
              <div v-for="(stat, index) in userStats" :key="index" class="stat-item text-center">
                <div class="stat-value font-semibold">{{ stat.value }}</div>
                <div class="stat-label text-xs opacity-70">{{ stat.label }}</div>
              </div>
            </div>
          </div>
        </div>
      </ElCard>

      <!-- User Details Card -->
      <ElCard class="flex-1 min-w-300px mt-0 md:mt-0" :body-style="{ padding: '20px' }">
        <template #header>
          <div class="flex justify-between items-center">
            <h3 class="m-0">{{ $t('page.userCenter.contactInfo') }}</h3>
            <ElButton type="primary" plain size="small" :icon="Edit">
              {{ $t('common.edit') }}
            </ElButton>
          </div>
        </template>
        
        <ElDescriptions :column="1" border>
          <ElDescriptionsItem :label="$t('page.manage.user.userPhone')">
            {{ userInfo.userPhone || '未设置' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="$t('page.manage.user.userEmail')">
            {{ userInfo.userEmail || '未设置' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="$t('page.manage.user.userGender')">
            <ElTag v-if="userInfo.userGender" type="primary">
              {{ $t(userGenderRecord[userInfo.userGender]) }}
            </ElTag>
            <span v-else>未设置</span>
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="$t('page.manage.user.userStatus')">
            <ElTag v-if="userInfo.status" :type="userInfo.status === 1 ? 'success' : 'warning'">
              {{ $t(enableStatusRecord[userInfo.status]) }}
            </ElTag>
            <span v-else>未设置</span>
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>
    </div>

    <!-- Recent Activity Card -->
    <ElCard class="mt-24px">
      <template #header>
        <div class="card-header">
          <h3 class="m-0">{{ $t('page.userCenter.recentActivity') }}</h3>
        </div>
      </template>
      
      <div class="timeline">
        <div v-for="(activity, index) in recentActivities" :key="index" class="timeline-item">
          <div class="timeline-dot" :style="{ 'background-color': themeStore.themeColor.primary }"></div>
          <div class="timeline-content">
            <div class="flex justify-between">
              <div class="activity-action">{{ activity.action }}</div>
              <div class="activity-time text-sm opacity-60">{{ activity.time }}</div>
            </div>
            <div class="activity-date text-sm opacity-70">{{ activity.date }}</div>
          </div>
        </div>
      </div>
    </ElCard>
  </div>
</template>

<style scoped lang="scss">
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
}

.upload-button {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.timeline {
  position: relative;
  padding-left: 20px;
}

.timeline-item {
  position: relative;
  padding-bottom: 20px;
  padding-left: 20px;
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-dot {
  position: absolute;
  left: -5px;
  top: 5px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: v-bind('themeStore.themeColor.primary');
}

.timeline-item:not(:last-child)::before {
  content: '';
  position: absolute;
  left: 0;
  top: 15px;
  height: calc(100% - 15px);
  width: 1px;
  background-color: #e0e0e0;
}

.activity-date {
  margin-top: 4px;
}

/* Dark mode adjustments */
:deep(.dark .timeline-item:not(:last-child)::before) {
  background-color: #4a4a4a;
}
</style>
